import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 28779
 * Date: 2023-11-26
 * Time: 17:44
 */
public class TcpEchoClient {
    public Socket socket = null;

    public TcpEchoClient(String ip, int port) throws IOException {
        socket = new Socket(ip, port);
    }

    public void start() {
        Scanner scanner = new Scanner(System.in);
        System.out.println("客户端启动！");

        try (InputStream inputStream = socket.getInputStream();
             OutputStream outputStream = socket.getOutputStream()){

            while (true) {
                // 1.从控制台输入
                System.out.print("->");
                String request = scanner.next();

                // 2.把请求发给服务器
                PrintWriter printWriter = new PrintWriter(outputStream);
                printWriter.println(request);

                printWriter.flush();

                // 3.从服务器读取响应
                Scanner scannerNetwork  = new Scanner(inputStream);
                String response = scannerNetwork.next();

                // 4.把响应打印下来
                System.out.println(response);

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        TcpEchoClient tcpEchoClient = new TcpEchoClient("127.0.0.1", 9090);
        tcpEchoClient.start();

    }
}
